<template>
  <view class="login-message-content">
    <view class="avatar-wrapper">
      <image class="avatar" :src="logoImg"></image>
    </view>
    <button class="wx-login-btn" open-type="getPhoneNumber" @getphonenumber="wxGetPhoneClick">微信账号一键登录</button>
  </view>
</template>

<script>
import Api, {fileUrlHost, imgHost} from "@/utils/api";
import {getItem, setItem} from "@/utils/storage";
import {GLOBAL_IS_LOGIN, GLOBAL_LOGIN_TIME, GLOBAL_OPEN_ID, GLOBAL_USER_ID, GLOBAL_USER_INFO} from "@/utils/const";
import {isEmpty, showToast} from "@/utils/utils";
import {getRequest, postRequest} from "@/utils/request";

/** 登录页信息内容组件 */
export default {
  name: "LoginMessage",
  data() {
    return {
      isGetTelephone: false, // 是否已获取到手机号
      isGetUserInfo: false, // 是否已获取到用户信息
      isUserRegister: false, // 是否是用户注册
      logoImg: imgHost + 'icon_logo_squre.png',
      userInfo: {
        avatarUrl: imgHost + 'my-head.png', // 微信头像
        nickName: '微信用户', // 微信昵称
        telephone: '', // 用户手机号
      },
    }
  },
  options: {
    styleIsolation: 'shared' // 解除样式隔离，否则自定义样式不生效
  },
  mounted() {
    console.log(getItem(GLOBAL_OPEN_ID))
  },
  methods: {
    // 微信授权获取手机号
    wxGetPhoneClick(e) {
      console.log('微信授权获取手机号: ', e)
      if (e.detail.errMsg === 'getPhoneNumber:ok') {
        console.log(e.detail.code)
        if (e.detail.code) {
          this.getDecryptTelephone(e.detail.code)
          return
        }

        /**
         * 如果开发者工具拿不到手机号加密code值，则采用写死手机号的方式进行调试
         */
        this.userInfo.telephone = '17327712814'
        this.isGetTelephone = true
        if (this.isGetTelephone && this.isGetUserInfo) {
          this.tryToSignInAction()
        }
      }
    },
    // 获取解密后的手机号
    getDecryptTelephone(code) {
      if (isEmpty(code)) return
      getRequest(Api.GetPhoneNumber, {code})
          .then(res => {
            console.log(res)
            this.userInfo.telephone = res
            this.isGetTelephone = true
            if (this.isGetTelephone) {
              this.tryToSignInAction()
            }
          })
    },
    // 获取手机号后登录
    tryToSignInAction() {
      const params = {
        userPhone: this.userInfo.telephone,
        openId: getItem(GLOBAL_OPEN_ID),
        cityCode: '东兴市东兴镇竹山村'
      }
      getRequest(Api.Login, params, '处理中...')
          .then(res => {
            console.log('尝试登录：', res)
            if (res === null) {
              this.isUserRegister = true
              this.userLoginClick()
            } else {
              showToast('登录成功！')
              // 手机号加密
              const telStart = res.userPhone.slice(0, 3)
              const telEnd = res.userPhone.slice(7)
              res.userPhone = telStart + '****' + telEnd

              if (res.wechatPic !== null && !isEmpty(res.wechatPic.zipPath)) {
                if (res.wechatPic.zipPath.indexOf('https://') !== -1) {
                  res.wechatPicPath = res.wechatPic.zipPath
                } else {
                  res.wechatPicPath = fileUrlHost + res.wechatPic.zipPath
                }
              } else {
                if (res.wechatPicPath) {
                  if (res.wechatPicPath.indexOf('/wechatProfilePic/') !== -1) {
                    res.wechatPicPath = fileUrlHost + res.wechatPicPath
                  }
                } else {
                  res.wechatPicPath = imgHost + 'my-head.png'
                }
              }

              // 金豆数
              if (isEmpty(res.goldPrice)) {
                res.goldPrice = 0
              }

              console.log('登录信息：', res)

              // 存储当前登录时间
              setItem(GLOBAL_LOGIN_TIME, new Date().getTime())
              // 存储用户信息
              setItem(GLOBAL_USER_ID, res.id)
              setItem(GLOBAL_USER_INFO, res)
              setItem(GLOBAL_IS_LOGIN, true)
              showToast('登录成功！')
              console.log(res)
              setTimeout(() => {
                uni.navigateBack({
                  delta: 1
                })
              }, 450)
            }
          })
    },
    // 登录(新用户注册)
    userLoginClick() {
      const params = {
        createBy: -1, //小程序用户默认-1
        userPhone: this.userInfo.telephone, //用户手机号
        openId: getItem(GLOBAL_OPEN_ID),
        cityCode: '东兴市东兴镇竹山村'
      }

      postRequest(Api.Register, params, '处理中...')
          .then(res => {
            console.log('注册成功：', res)
            // 手机号加密
            const telStart = res.userPhone.slice(0, 3)
            const telEnd = res.userPhone.slice(7)
            res.userPhone = telStart + '****' + telEnd

            if (res.wechatPic !== null && !isEmpty(res.wechatPic.zipPath)) {
              if (res.wechatPic.zipPath.indexOf('https://') !== -1) {
                res.wechatPicPath = res.wechatPic.zipPath
              } else {
                res.wechatPicPath = fileUrlHost + res.wechatPic.zipPath
              }
            } else {
              if (res.wechatPicPath) {
                if (res.wechatPicPath.indexOf('/wechatProfilePic/') !== -1) {
                  res.wechatPicPath = fileUrlHost + res.wechatPicPath
                }
              } else {
                res.wechatPicPath = imgHost + 'my-head.png'
              }
            }

            // 金豆数
            if (isEmpty(res.goldPrice)) {
              res.goldPrice = 0
            }

            // 存储当前登录时间
            setItem(GLOBAL_LOGIN_TIME, new Date().getTime())
            // 存储用户信息
            setItem(GLOBAL_USER_ID, res.id)
            setItem(GLOBAL_USER_INFO, res)
            setItem(GLOBAL_IS_LOGIN, true)
            showToast('登录成功！')
            setTimeout(() => {
              uni.navigateBack({
                delta: 1
              })
            }, 450)
          })
    }
  }
}
</script>

<style>
page {
  background-color: #F3F3F3;
}
</style>
<style scoped lang="scss">
.login-message-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  .avatar-wrapper {
    display: flex;
    justify-content: center;
    margin-top: 180rpx;
    width: 130rpx;
    height: 130rpx;
    border-radius: 65rpx;
    overflow: hidden;
    .avatar {
      width: 100%;
      height: 100%;
    }
  }
  .wx-login-btn {
    width: 80%;
    margin: 88rpx 0;
    height: 80rpx;
    font-size: 34rpx;
    font-weight: 500;
    line-height: 80rpx;
    color: #FFFFFF;
    background-color: #16AA68;
    border-radius: 40rpx;
  }
  .wx-login-btn::after {
    border: none;
  }
  .no-login-btn {
    color: #7C7C7C;
    background-color: #CECECE;
  }
}
</style>
